﻿using MailKit.Net.Imap;
using MailKit.Search;
using MailKit.Security;
using MailKit;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using RecordBill.Dtos;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Microsoft.VisualBasic;
using System.Security.Cryptography;

namespace RecordBill.Core
{
    public class QQMailService
    {
        private readonly string _host = "imap.qq.com";
        private readonly int _port = 993;

        public async Task<List<EmailMessage>> ReadEmailsWithDownloadLinksAsync(
            string email, string password, int maxEmails = 10)
        {
            var emailsWithLinks = new List<EmailMessage>();

            using (var client = new ImapClient())
            {
                try
                {
                    // 连接到QQ邮箱IMAP服务器
                    await client.ConnectAsync(_host, _port, SecureSocketOptions.SslOnConnect);
                    await client.AuthenticateAsync(email, password);

                    // 选择收件箱
                    var inbox = client.Inbox;
                    await inbox.OpenAsync(FolderAccess.ReadWrite);

                    // 获取最新的邮件
                    var uids = await inbox.SearchAsync(SearchQuery.NotDeleted);
                    var recentUids = uids.TakeLast(maxEmails).Reverse(); // 从最新开始
                                                                         // 假设你已经连接并打开了收件箱 (inbox)
                                                                         // 首先，获取或创建目标文件夹（例如"已删除"）
                    var trashFolder = client.GetFolder("已删除"); // 文件夹名称可能因邮箱服务商而异，也可能是 "Trash"
                                                               // 确保文件夹存在，必要时需要创建

                    foreach (var uid in recentUids)
                    {
                        var message = await inbox.GetMessageAsync(uid);

                        // 本地过滤：检查主题是否包含关键词
                        if (message.Subject != null &&
                            (message.Subject.Contains("微信支付") ||
                             message.Subject.Contains("微信账单")))
                        {



                            var downloadLinks = ExtractDownloadLinks(message);

                            if (downloadLinks.Any())
                            {
                                emailsWithLinks.Add(new EmailMessage
                                {
                                    Uid = uid,
                                    Subject = message.Subject,
                                    From = message.From.ToString(),
                                    Date = message.Date.DateTime,
                                    DownloadLinks = downloadLinks,
                                    Body = GetMessageBody(message)
                                });
                            }

                            await inbox.MoveToAsync(uid, trashFolder);

                        }
                    }

                    await client.DisconnectAsync(true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"错误: {ex.Message}");
                }
            }

            return emailsWithLinks;
        }

        public async Task<List<EmailMessage>> ReadEmailsWithDownloadLinksAsync(
            string email, string password, int billType, int maxEmails = 10)
        {
            var subjectKeys = new List<string>();
            if (billType == 1)
            {
                subjectKeys.Add("微信支付");
                subjectKeys.Add("微信账单");
            }
            else if (billType == 2)
            {
                subjectKeys.Add("支付宝-记账");
            }
            else
            {
                return new List<EmailMessage>();
            }

            var emails = await GetEmails(email, password, subjectKeys);
            var emailsWithLinks = new List<EmailMessage>();
            if (emails?.Count>0)
            {
                foreach (var message in emails)
                {
                    if(billType==1)
                    {
                        var downloadLinks = ExtractDownloadLinks(message);
                        if (downloadLinks.Any())
                        {
                            emailsWithLinks.Add(new EmailMessage
                            {
                                Subject = message.Subject,
                                From = message.From.ToString(),
                                Date = message.Date.DateTime,
                                DownloadLinks = downloadLinks,
                                Body = GetMessageBody(message)
                            });
                        }
                    }
                    else
                    {
                        var localFilePaths = await ProcessAttachmentsAsync(message, ConfigSettings.DownloadDir, email);
                        if (localFilePaths.Any())
                        {
                            emailsWithLinks.Add(new EmailMessage
                            {
                                Subject = message.Subject,
                                From = message.From.ToString(),
                                Date = message.Date.DateTime,
                                DownloadLinks = localFilePaths,
                            });
                        }
                    }
                }
            }
            return emailsWithLinks;

        }
        private async Task<List<string>> ProcessAttachmentsAsync(MimeMessage message,
       string downloadPath, string emailId)
        {
            List<string> filePaths = new List<string>();
            foreach (var attachment in message.Attachments)
            {
                if (attachment is MimePart part)
                {
                    var fileName = part.FileName;

                    // 创建下载目录
                    if (!Directory.Exists(downloadPath))
                        Directory.CreateDirectory(downloadPath);

                    var filePath = Path.Combine(downloadPath,
                        $"{fileName}");

                    // 保存附件
                    using var stream = File.Create(filePath);
                    await part.Content.DecodeToAsync(stream);

                    filePaths.Add(filePath);
                }
            }
            return filePaths;
        }


        private async Task<List<MimeMessage>> GetEmails(string email, string password, List<string> Subjectkeys)
        {
            List<MimeMessage> list = new List<MimeMessage>();

            using (var client = new ImapClient())
            {
                try
                {
                    // 连接到QQ邮箱IMAP服务器
                    await client.ConnectAsync(_host, _port, SecureSocketOptions.SslOnConnect);
                    await client.AuthenticateAsync(email, password);

                    // 选择收件箱
                    var inbox = client.Inbox;
                    await inbox.OpenAsync(FolderAccess.ReadWrite);

                    // 获取最新的邮件
                    var uids = await inbox.SearchAsync(SearchQuery.NotDeleted);
                    var recentUids = uids.TakeLast(10).Reverse(); // 从最新开始
                                                                  // 假设你已经连接并打开了收件箱 (inbox)
                                                                  // 首先，获取或创建目标文件夹（例如"已删除"）
                    var trashFolder = client.GetFolder("已删除"); // 文件夹名称可能因邮箱服务商而异，也可能是 "Trash"
                                                               // 确保文件夹存在，必要时需要创建

                    foreach (var uid in recentUids)
                    {
                        var message = await inbox.GetMessageAsync(uid);

                        // 本地过滤：检查主题是否包含关键词
                        if (message.Subject != null &&
                          Subjectkeys.Any(a => message.Subject.Contains(a)))
                        {
                            list.Add(message);
                            await inbox.MoveToAsync(uid, trashFolder);

                        }
                    }
                    await client.DisconnectAsync(true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"错误: {ex.Message}");
                }
            }

            return list;
        }


        private List<string> ExtractDownloadLinks(MimeMessage message)
        {
            var links = new List<string>();
            var body = GetMessageBody(message);

            if (!string.IsNullOrEmpty(body))
            {
                // 匹配常见的下载链接模式
                var urlPatterns = new[]
                {
                    @"https?://[^\s""<>]+\.(zip|rar|7z|tar|gz|exe|msi|dmg|pkg|deb|rpm|apk|pdf|doc|docx|xls|xlsx|ppt|pptx)[^\s""<>]*",
                    @"https?://[^\s""<>]*(download|dl|file|attachment)[^\s""<>]*",
                    @"https?://[^\s""<>]*\.(baidu|aliyun|tencent|qq|weiyun)\.com[^\s""<>]*",
                    @"https?://pan\.baidu\.com[^\s""<>]*",
                    @"https?://[^\s""<>]*\.cloud[^\s""<>]*"
                };

                foreach (var pattern in urlPatterns)
                {
                    var matches = Regex.Matches(body, pattern, RegexOptions.IgnoreCase);
                    links.AddRange(matches.Select(m => m.Value));
                }

                // 从HTML内容中提取链接
                if (message.HtmlBody != null)
                {
                    var htmlLinks = ExtractLinksFromHtml(message.HtmlBody);
                    links.AddRange(htmlLinks);
                }
            }

            // 去重并返回
            return links.Distinct().ToList();
        }

        private List<string> ExtractLinksFromHtml(string html)
        {
            var links = new List<string>();
            var hrefPattern = @"href\s*=\s*[""']?([^""'\s>]+)[""']?";
            var matches = Regex.Matches(html, hrefPattern, RegexOptions.IgnoreCase);

            foreach (Match match in matches)
            {
                if (match.Groups.Count > 1)
                {
                    var link = match.Groups[1].Value;
                    if (IsDownloadLink(link))
                    {
                        links.Add(link);
                    }
                }
            }

            return links;
        }

        private bool IsDownloadLink(string url)
        {
            if (string.IsNullOrEmpty(url)) return false;

            var downloadExtensions = new[]
            {
                ".zip", ".rar", ".7z", ".tar", ".gz", ".exe", ".msi",
                ".dmg", ".pkg", ".deb", ".rpm", ".apk", ".pdf",
                ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx"
            };

            var downloadKeywords = new[]
            {
                "download", "dl", "file", "attachment", "pan.baidu"
            };

            return downloadExtensions.Any(ext => url.ToLower().Contains(ext)) ||
                   downloadKeywords.Any(keyword => url.ToLower().Contains(keyword));
        }

        private string GetMessageBody(MimeMessage message)
        {
            // 优先返回HTML内容，如果没有则返回文本内容
            if (!string.IsNullOrEmpty(message.HtmlBody))
            {
                return message.HtmlBody;
            }


            return message.TextBody ?? string.Empty;
        }
    }

}
